☰ See All Chapters |
How to iterate array in JavaScript ES6
for loop
for loop can iterate through the elements of an array as below example:
let directions = ["north", "south", "east", "west"]; for(let i=0; i<3; i++) { console.log(directions[i]); } |
for..in loop
In for..in loop, the loop iterator takes the numeric index of the loop iteration, starting with 0.
Example:
let directions = ["north", "south", "east", "west"]; for(let i in directions) { console.log(directions[i]); } |
for..of loop
In for..of loop, the loop iterator takes the each value of the array one after the other, starting with first element.
Example:
let directions = ["north", "south", "east", "west"]; for(let i of directions) { console.log(i); } |
JavaScript ES6 Array methods
Methods | Description | Example |
Array.from() | It converts array-like values and iterable values into arrays. | const myArr = Array.from("ABCDEFG"); console.log(myArr); Output: ['A', 'B', 'C', 'D', 'E', 'F', 'G'] |
find() | It finds a value from an array, based on the specific criteria that are passed to this method. | const numbers = [4, 9, 18, 50, 60]; let first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 20; } console.log(first); 50
|
findIndex() | The findIndex() returns the index of the first element of the given array that satisfies the given condition. | const numbers = [4, 9, 18, 50, 60]; let first = numbers.findIndex(myFunction); function myFunction(value, index, array) { return value > 20; } console.log(first); 3
|
keys() | It returns an array iterator object along with the keys of the array. | const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = fruits.keys(); for (let x of keys) { console.log(x); } Output: 0 1 2 3 |
All Chapters